package com.example.security.social;

import com.example.security.properties.SecurityProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.social.config.annotation.EnableSocial;
import org.springframework.social.config.annotation.SocialConfigurerAdapter;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.ConnectionSignUp;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.connect.jdbc.JdbcUsersConnectionRepository;
import org.springframework.social.security.SpringSocialConfigurer;

import javax.sql.DataSource;

@Order(1)
@Configuration
@EnableSocial
public class SocialConfig extends SocialConfigurerAdapter {
    @Autowired
    DataSource dataSource;
    @Autowired
    SecurityProperties securityProperties;
    @Autowired(required = false)
    private ConnectionSignUp connectionSignUp;

    @Override
    public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
        //暂时不做加解密操作,存到user-connection表中
        JdbcUsersConnectionRepository repository = new JdbcUsersConnectionRepository(dataSource, connectionFactoryLocator, Encryptors.noOpText());
        //repository.setTablePrefix("login_");//给表加前缀
        if(connectionSignUp != null) {
            repository.setConnectionSignUp(connectionSignUp);//不让跳转到注册页面，直接默认注册一个用户
        }
        return repository;
    }

    @Bean//处理第三方QQ的过滤器
    public SpringSocialConfigurer loginSocialSecurityConfig() {
        //设置自定义的第三方路径，默认是/auth
        String filterProcessesUrl = securityProperties.getSocial().getFilterProcessesUrl();
        LoginSpringSocialConfigurer configurer = new LoginSpringSocialConfigurer(filterProcessesUrl);//自定义的访问url-->/auth
        //configurer.signupUrl(securityProperties.getBrowser().getSignUpUrl());
        return configurer;
    }
}
